/**
 *
 */
package org.insia.smartposse.manager;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.insia.smartposse.mapping.Projects;
import org.insia.smartposse.mapping.dao.ProjectsDAO;

/**
 * Manage a list of Project
 *
 * @author cmougel
 *
 */
public final class ProjectsListManager extends ArrayList {

	public static final int NOTCOMPLETE = 0;
	public static final int COMPLETE = 1;
	public static final int ALL = 2;

	private List<Projects> _projects = new ArrayList<Projects>();
	private final ProjectsDAO _dao = new ProjectsDAO();
	private final Session _session;
	private Boolean _search = false;
	private int _complete = ProjectsListManager.NOTCOMPLETE;
	private String _subject = null;
	private String _shortDescription = null;

	/**
	 * Get All Project
	 */
	public ProjectsListManager(){
		_session = _dao.getSession();
	}


	/**
	 * Constructor with define if list is with complete or not
	 *
	 * @param complete
	 */
	public ProjectsListManager(int complete){
		this();
		_complete = complete;
	}

	/**
	 * With this Constructor, there are a filter with the Subject
	 *
	 * @param b
	 * @param subject
	 */
	public ProjectsListManager(int complete, String subject) {
		this(complete);
		_subject  = subject;
	}

	/**
	 * Start the query if not already start
	 *
	 */
	private void search(){
		if (!_search){
			_projects = _dao.search(_session, _complete, _subject, _shortDescription);
			_search = true;
		}
	}

	/**
	 * Destruct and close the session
	 */
	public void finalize(){
		ProjectsDAO.closeCurrentSession();
	}

	@Override
	public ProjectManager get(int index) {
		search();
		return new ProjectManager(_projects.get(index));
	}

	@Override
	public int size() {
		search();
		return _projects.size();
	}


	/**
	 * Define the Subject for search and re-act the search if necessary
	 *
	 * @param subject
	 */
	public void setSubject(String subject) {
		if ("" != subject && null != subject){
			_subject = subject;
			_search = false;
		}
	}


	public void setShortDescription(String shortDescription) {
		if ("" != shortDescription && null != shortDescription){
			_shortDescription  = shortDescription;
			_search = false;
		}
	}
}
